package com.thread.upload;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class MultithreadUpload extends Thread {

	private int startRownum;

	private int endRownum;

	private Connection connection = null;

	public MultithreadUpload(int startRownum, int endRownum, Connection connection) {
		super();
		this.startRownum = startRownum;
		this.endRownum = endRownum;
		this.connection = connection;
	}

	public void run() {
		Statement statement = null;
		ResultSet rs = null;
		StringBuffer sb = new StringBuffer();
		if (connection != null) {
			try {
				// 读取数据
				statement = connection.createStatement();
				String sql = " select a.* from (" + " select t.*,rownum rn  from transact_log_qry t  ) a "
						+ "where a.rn between " + startRownum + " and " + endRownum + " order by a.log_id";
				rs = statement.executeQuery(sql);
				while (rs.next()) {
					long logId = rs.getLong("LOG_ID");
					String transactionId = rs.getString("TRANSACTION_ID");
					String line = logId + " " + transactionId + "\n";
					sb.append(line);
				}
				// 创建中间文件
				String fileName = "E:/xxxx/transact_qry_" + startRownum + "_" + endRownum;
				String serviceFileName = "transact_qry_" + startRownum + "_" + endRownum;
				File file = new File(fileName);
				if (!file.exists()) {
					boolean createNewFile = file.createNewFile();
					if (createNewFile) {
						FileUtil.writeFile(fileName, sb.toString());
					}
				}

				// 上传ftp
				boolean upload = FtpUtil.upload("/transact_log_qry", serviceFileName, fileName);
				if (upload) {
					// 上传文件成功 删除文件
					boolean deleteFile = FileUtil.deleteFile(fileName);
					if (deleteFile) {
						System.out.println("删除文件【" + fileName + "】成功");
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				// try {
				// if (rs != null)
				// rs.close();
				// if (statement != null)
				// statement.close();
				// if (connection != null)
				// connection.close();
				// } catch (SQLException e) {
				// e.printStackTrace();
				// }

			}
		}
	}

}
